package org.siberia.server.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.Version;

import com.google.gwt.user.client.rpc.IsSerializable;

@Entity
public class User
{
	@Id
	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long id;
	
	/* name */
	public String username;
	
	/** version */
	@Version
	public Integer version;
	
	public static EntityManager entityManager()
	{
		return EMF.get().createEntityManager();
	}
	
	public static User findUser(Long _id)
	{
		User result = null;
		
		if ( _id != null )
		{
			EntityManager manager = entityManager();
			try
			{	result = manager.find(User.class, _id); }
			finally
			{	manager.close(); }
		}
		
		return result;
	}
	
	public static User findUserByName(String _username)
	{
		User result = null;
		
		if ( _username != null )
		{
			EntityManager manager = entityManager();
			try
			{	
				Query query = manager.createQuery("select o from User o where o.username=:username");
				query.setParameter("username", _username);
				result = (User)query.getSingleResult();
			}
			catch(NoResultException e)
			{
				// okay no result
			}
			finally
			{	manager.close(); }
		}
		
		return result;
	}
	
	public void persist()
	{
		EntityManager manager = entityManager();
		try
		{	manager.persist(this); }
		finally
		{	manager.close(); }
	}
	
	public void remove()
	{
		EntityManager manager = entityManager();
		try
		{	
			User _user = manager.find(User.class, this.id);
			manager.remove(_user);
		}
		finally
		{	manager.close(); }
		
	}
	
	public static void deleteAll()
	{
		EntityManager manager = entityManager();
		
		try
		{
			Query query = manager.createQuery("DELETE from User o");
			query.executeUpdate();
		}
		finally
		{	manager.close(); }
	}
	
	public static List<User> findAll()
	{
		List<User> result = null;
		
		EntityManager manager = entityManager();
		try
		{	
			Query query = manager.createQuery("select o from User o");
			result = (List<User>)query.getResultList();
			result = new ArrayList<User>(result);
		}
		catch(NoResultException e)
		{
			// okay no result
		}
		finally
		{	manager.close(); }
		
		if ( result == null )
		{
			result = Collections.<User>emptyList();
		}
		
		return result;
	}
}
